<template>
  <div>
    <van-nav-bar left-text="返回" title="提交盘查" left-arrow @click-left="onClickLeft">
    </van-nav-bar>
    <van-form @submit="onSubmit" @failed="onFailed" ref="vanFormRef" :key="formKey">
      <!-- 班前检查内容 -->
      <van-cell-group inset>
        <van-cell-group>
          <van-field required v-model="formState.assetTag" name="assetTag" label="资产标签号:" placeholder="请输入资产标签号"
            :rules="[{ required: true, message: '请输入资产标签号' }]" @blur="handleChange" />
        </van-cell-group>
        <van-field v-model="formState.equipmentName" disabled="true" required name="equipmentName" label="资产名称:"
          placeholder="请输入资产名称" :rules="[{ required: true, message: '请输入资产名称' }]" />
        <van-field v-model="formState.specificLocation" disabled="true" required name="specificLocation" label="具体位置:"
          placeholder="请输入具体位置" :rules="[{ required: true, message: '请输入具体位置' }]" />
        <van-field v-model="formState.responsiblePersonName" disabled="true" required name="responsiblePersonName"
          label="责任人:" placeholder="请输入责任人" :rules="[{ required: true, message: '请输入责任人' }]" />
        <van-field v-model="formState.responsiblePersonId" disabled="true" required name="responsiblePersonId"
          label="责任人编号:" placeholder="请输入责任人编号" :rules="[{ required: true, message: '请输入责任人编号' }]" />
        <van-field v-model="formState.signature" disabled="true" type="textarea" required name="signature" label="当前位置:"
          placeholder="请输入当前位置" :rules="[{ required: true, message: '请输入当前位置' }]" />
        <van-field required name="checkResult" label="是否合格：" :rules="[{ required: true, message: '请选择是否' }]">
          <template #input>
            <van-radio-group v-model="formState.checkResult" direction="horizontal">
              <van-radio name="1">是</van-radio>
              <van-radio name="0">否</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field v-model="formState.checkNotes" required name="checkNotes" label="情况说明：" type="textarea"
          placeholder="请输入发现问题" rows="5" autosize :rules="[{ required: true, message: '请输入使用情况' }]" />
        <!-- <van-field class="groupField" v-model="formState.fileList" required name="fileList" label="相关图片上传："
          :rules="[{ required: true, message: '请上传相关图片' }]">
          <template #input>
            <van-uploader class="addUploader" v-model="fileList" :after-read="onRead">
              <van-icon name="photograph" />
            </van-uploader>
          </template>
        </van-field> -->
        <van-field class="groupField" required name="fileList" label="相关图片上传："
          :rules="[{ required: true, message: '请上传相关图片' }]">
          <template #input>
            <van-uploader class="addUploader" accept="image/*" v-model="fileList" :after-read="onRead"
              :before-delete="beforeDelete" :capture="isAndroid ? 'camera' : null">
              <van-icon name="photograph" />
            </van-uploader>
          </template>
        </van-field>
      </van-cell-group>
      <div style="margin: 16px;">
        <van-button  round block type="primary" native-type="submit">
          提交
        </van-button>
      </div>

    </van-form>
    <van-popup v-model:show="loadingShow" style="background: transparent;">
      <div>
        <van-loading type="spinner" color="white" style="overflow: hidden;" />
      </div>

    </van-popup>
  </div>
</template>
<script setup>
import { ref, onMounted } from "vue"
import { useRoute } from "vue-router";
import EquipmentEditApi from "./api/equipmentEdit.js"
import { Toast } from "vant";
import { getToken } from '../../utils/auth'
import { parseTime } from "../../utils";
import axios from "axios"
import { useStore } from 'vuex'
import myBMap from "../../utils/myBMap.js"
const store = useStore()
const loadingShow = ref(false)
const fileLoadingShow = ref(false)
const route = useRoute()
const textCode = ref()
const formKey = ref(0)
const fileList = ref([

])
const picId = ref([])
const isAndroid = /Android|Linux/.test(navigator.userAgent)
const formState = ref({
  assetTag: undefined,
  equipmentName: undefined,
  specificLocation: undefined,
  responsiblePersonName: undefined,
  responsiblePersonId: undefined,
  checkResult: undefined,
  checkNotes: undefined,
  fileList: [],
  signature: ""
})
getLocation()
onMounted(() => {

  if (route.query.textCode) {
    formState.value.assetTag = route.query.textCode
    handleChange()
  }
})

function getLocation() {
  //Toast("如长时间未获取办理区域请手动选择");
  myBMap.init().then(() => {
    let geolocation = new BMap.Geolocation(); // 创建百度地理位置实例，代替 navigator.geolocation
    geolocation.getCurrentPosition(function (e) {
      if (this.getStatus() == BMAP_STATUS_SUCCESS) {
        // 百度 geolocation 的经纬度属性不同，此处是 point.lat 而不是 coords.latitude
        let point = new BMap.Point(e.point.lng, e.point.lat);
        let gc = new BMap.Geocoder();
        gc.getLocation(point, function (rs) {
          console.log(rs);
          formState.value.signature = rs.address

        });
      } else {
        Toast.fail("定位失败，请手动选择区域或重新定位");
      }
    });
  });
}
textCode.value = route.query.textCode
const onSubmit = async () => {
  if(fileLoadingShow.value)return
  loadingShow.value = true

  EquipmentEditApi.equipmentcheckAdd({
    equipmentId: formState.value.assetTag,
    departmentId: store.getters.deptId,
    checkPersonId: store.getters.userid,
    checkResult: formState.value.checkResult,
    checkNotes: formState.value.checkNotes,
    checkPersonName: store.getters.name,
    signature: formState.value.signature,
    picss: picId.value
  }).then(res => {
    loadingShow.value = false
    if (res.data.code == 200) {
      Toast.success("盘查成功")
      onClickLeft()
    }
  }).catch(error => {
    loadingShow.value = false
  })

}
const onFailed = () => { }

const onClickLeft = () => {

  if (route.query.textCode) {
    history.go(-2);
  } else {
    history.back()
  }

}
const handleChange = () => {
  EquipmentEditApi.getDquipmenttableD({ searchTime: parseTime(new Date(), '{y}-{m}'), assetTag: formState.value.assetTag }).then(res => {
    if (res.data.code == 200 && res.data.data) {
      formState.value = Object.assign(formState.value, res.data.data)
    } else {
      Toast.fail(res.data.message)
      for (const key in formState.value) {
        if (Object.hasOwnProperty.call(formState.value, key)) {
          if (key != 'assetTag') {
            formState.value[key] = undefined
          }

        }
      }
      getLocation()
    }

  })
}


async function uploadFile(files) {
  fileLoadingShow.value=true
  return new Promise(async (resolve, reject) => {
    const formData = new FormData();
    for (let i = 0; i < files.length; i++) {
      formData.append('file', files[i]); // 添加每个文件到 FormData 中
    }
    try {
      const response = await axios.post(import.meta.env.VITE_APP_BASE_API + '/ImageUpload/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          "Authorization": getToken()
        }
      });

      if (response.status != 200) {
        throw new Error();
      }
      
      resolve(response.data.uploadedFiles)
    } catch (error) {
      Toast.fail('文件上传失败');
      reject(false)
    }
  })
}

function base64ToFile(base64Str, fileName) {
  var arr = base64Str.split(',')
  var mime = arr[0].match(/:(.*?);/)[1] // base64解析出来的图片类型
  // 对base64串进行操作，去掉url头，并转换为byte   atob为window内置方法
  var bstr = atob(arr[1])
  var len = bstr.length
  var ab = new ArrayBuffer(len) // 将ASCII码小于0的转换为大于0
  var u8arr = new Uint8Array(ab) //
  while (len--) {
    u8arr[len] = bstr.charCodeAt(len)
  };
  // 创建新的 File 对象实例[utf-8内容，文件名称或者路径，[可选参数，type：文件中的内容mime类型]]
  return new File([u8arr], fileName, {
    type: mime
  })
}
const onRead = (file) => {

  uploadFile([file.file]).then(res => {
    picId.value.push(res[0].fileId)
    fileLoadingShow.value=false
  }).catch(error => {

    let deleId = fileList.value.findIndex(targe => {
      return targe.objectUrl == file.objectUrl
    })
    if (deleId != -1) {
      fileList.value.splice(deleId, 1)
    }
    fileLoadingShow.value=false
  })


}
const beforeDelete = (file) => {
  let deleId = fileList.value.findIndex(targe => {
    return targe.objectUrl == file.objectUrl
  })
  if (deleId != -1) {
    fileList.value.splice(deleId, 1)
    picId.value.splice(deleId, 1)
  }
}
</script>
<style>
.groupField .van-cell__title {
  width: 100%;
  color: #646566;
  margin-bottom: 10px;
}

.groupField {
  display: flex;
  flex-direction: column;
}

.addUploader .van-uploader__input-wrapper {
  display: flex;
  align-items: center;
  padding: 20px;
}

.addUploader .van-icon {
  font-size: 30px;
}

.van-field--disabled .van-field__label {
  color: #646566;
}

/* .van-field__control[disabled]::placeholder{
  -webkit-text-fill-color: #323233;

} */
.van-field__control[disabled] {
  -webkit-text-fill-color: #323233 !important;
}

.van-field__control[disabled]::placeholder {
  -webkit-text-fill-color: #c8c9cc !important;
}
</style>